package com.welfare.entity.dto;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.welfare.entity.Welfare;


public class WelfareQueryDTO {
	private Long id;
	private String welfCode;//编号
	private String welfName;//名字
	private String description;//描述
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getWelfCode() {
		return welfCode;
	}
	public void setWelfCode(String welfCode) {
		this.welfCode = welfCode;
	}
	public String getWelfName() {
		return welfName;
	}
	public void setWelfName(String welfName) {
		this.welfName = welfName;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	//提供static的工具方法：根据当前 userQueryDTO 对象来组装动态查询条件
	public static Specification<Welfare> getSpecification(WelfareQueryDTO userQueryDTO)
	{
		Specification<Welfare> spec = new Specification<Welfare>() {
			public Predicate toPredicate(Root<Welfare> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//1.Predicate查询条件集合
				 List<Predicate> list = new ArrayList<Predicate>(); 
				 
				//2.根据 QueryDTO数据字段的值进行判断以及条件的组装
				 if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getWelfName())) {
					 Predicate  p1 =  cb.like(root.get("welfName").as(String.class),"%"+ userQueryDTO.getWelfName() + "%");
					 list.add(p1);
				 }
				 if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getWelfCode())) {
					 Predicate  p2 =  cb.like(root.get("welfCode").as(String.class),"%"+ userQueryDTO.getWelfCode() + "%");
					 list.add(p2);
				 }
				 //3.Predicate查询条件集合的 size 创建对应的Predicate查询条件数组
				 Predicate[] p = new Predicate[list.size()];  
				 //4.CriteriaBuilder的and 函数组装 查询条件数组
				 return cb.and(list.toArray(p));  
			}
		};
		return spec;
	}
}
